package com.javaweb.dao.impl;

import com.javaweb.dao.CategoryDao;
import com.javaweb.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author Wanghai
 * @date 2024/10/9
 */
@Repository
public class CategoryDaoImpl implements CategoryDao {
    @Autowired
    JdbcTemplate jdbcTemplate ;
    @Override
    public int insert(Category category) {
        String sql="insert into tb_category(name,`order`,parent_id,create_time,update_time)" +
                "values (?,?,?,?,?)";
        Object [] args = new Object[]{
                category.getName(),
                category.getOrder(),
                category.getParentId(),
                new java.sql.Date(category.getCreateTime().getTime()),
                new java.sql.Date(category.getUpdateTime().getTime())}
                ;
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int deleteById(String categoryId) {
        String sql = "DELETE FROM tb_category WHERE id = ?";
        return jdbcTemplate.update(sql, categoryId);
    }

    @Override
    public List<Category> findAllCategories() {
        String sql = "SELECT * FROM tb_category";
        return jdbcTemplate.query(sql, new CategoryRowMapper());
    }

    // 自定义 RowMapper 实现
    private static class CategoryRowMapper implements RowMapper<Category> {
        @Override
        public Category mapRow(ResultSet rs, int rowNum) throws SQLException {
            Category category = new Category();
            category.setId(rs.getInt("id"));
            category.setName(rs.getString("name"));
            category.setOrder(rs.getInt("order"));
            category.setParentId(rs.getInt("parent_id"));
            category.setCreateTime(rs.getTimestamp("create_time"));
            category.setUpdateTime(rs.getTimestamp("update_time"));
            return category;
        }
    }

    @Override
    public Category getCategoryByname(String categoryname) {
        String sql = "SELECT * FROM tb_category WHERE name = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{categoryname},new CategoryRowMapper() );
    }

    @Override
    public void addCategory(Category category) {

    }

    @Override
    public void deleteCategory(String categoryId) {

    }
}
